<?php

namespace APP\api;

use APP\api\admin\plugin;
use APP\DI;
use APP\program\admin\Cache;
use APP\program\admin\Error;
use APP\program\admin\Setting;
use APP\program\admin\user\Notification;
use APP\program\admin\Verify;
use APP\program\Resource;
use LyApi\core\classify\VIEW;
use LyApi\core\design\Register;
use LyApi\core\request\Request;
use LyApi\tools\Config;
use LyApi\tools\Launch;
use LyApi\tools\Template;
use Plugin\LyMaster\LyMaster;

class admin extends VIEW
{

    private $resources;
    private $admin_plugin;
    private $develop_setting;

    // 初始化函数
    public function __construct()
    {
        $this->resources = new Resource();
        $this->admin_plugin = new LyMaster();
        $this->develop_setting = Config::getConfig('develop', 'admin', 'json');
    }

    public function verify()
    {
        if (!Verify::isLogin()) {
            return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/login.html'), [
                'domain' => $this->resources->Domain(),
                'resource' => $this->resources->Domain() . '/resource/admin/'
            ]);
        } else {
            return "<script>location.href = '/admin'</script>";
        }
    }

    // 加载 Admin 系统配置
    public function pinit()
    {
        $this->SetHeader('Content-type: application/json');

        $pluginPages = [];

        $pmanager = Register::Get('PManager');
        $pmanager->pluginPages();

        $plugins = Register::Get('AdminPages');
        if (gettype($plugins) == 'array') {
            foreach ($plugins as $pn => $pv) {

                $childs = [];

                foreach ($pv as $cn => $cv) {
                    array_push($childs, $cv);
                }

                array_push($pluginPages, [
                    'title' => $pn,
                    'icon' => 'fa fa-support',
                    'href' => '',
                    'target' => '_self',
                    'child' => $childs
                ]);
            }
        }

        array_push($pluginPages, [
            'title' => '插件列表',
            'icon' => 'fa fa-list',
            'href' => '/admin/plugin?to=manage',
            'target' => '_self'
        ]);

        $menuInfo = [
            [
                'title' => '基础配置',
                'icon' => 'fa fa-address-book',
                'href' => '',
                'target' => '_self',
                'child' => [
                    [
                        'title' => '接口管理',
                        'icon' => 'fa fa-key',
                        'href' => '',
                        'target' => '_self',
                        'child' => [
                            [
                                'title' => '接口列表',
                                'icon' => 'fa fa-list',
                                'href' => '/admin/page?type=apis&which=list',
                                'target' => '_self'
                            ],
                            [
                                'title' => '模板列表',
                                'icon' => 'fa fa-file-code-o',
                                'href' => '/admin/page?type=template&which=list',
                                'target' => '_self'
                            ]
                        ]
                    ], [
                        'title' => '用户管理',
                        'icon' => 'fa fa-user',
                        'href' => '',
                        'target' => '_self',
                        'child' => [
                            [
                                'title' => '用户列表',
                                'icon' => 'fa fa-list',
                                'href' => '/admin/page?type=users&which=list',
                                'target' => '_self'
                            ],
                            [
                                'title' => '用户权限',
                                'icon' => 'fa fa-user-plus',
                                'href' => '/admin/page?type=users&which=level.list',
                                'target' => '_self'
                            ]
                        ]
                    ], [
                        'title' => '数据管理',
                        'icon' => 'fa fa-database',
                        'href' => '',
                        'target' => '_self',
                        'child' => [
                            [
                                'title' => '数据库列表',
                                'icon' => 'fa fa-list',
                                'href' => '/admin/page?type=dbs&which=list',
                                'target' => '_self'
                            ],
                            [
                                'title' => 'SQL 控制台',
                                'icon' => 'fa fa-archive',
                                'href' => '/admin/page?type=dbs&which=sql',
                                'target' => '_self'
                            ]
                        ]
                    ], [
                        'title' => '配套工具',
                        'icon' => 'fa fa-bug',
                        'href' => '',
                        'target' => '_self',
                        'child' => [
                            [
                                'title' => '代码编辑器',
                                'icon' => 'fa fa-code',
                                'href' => '/admin/coder',
                                'target' => '_blank'
                            ],
                            [
                                'title' => '代码生成器',
                                'icon' => 'fa fa-cube',
                                'href' => '/admin/maker',
                                'target' => '_blank'
                            ], [
                                'title' => '快捷命令行',
                                'icon' => 'fa fa-server',
                                'href' => '/admin/cmder',
                                'target' => '_self'
                            ]
                        ]
                    ],
                    [
                        'title' => '系统设置',
                        'icon' => 'fa fa-cog',
                        'href' => '/admin/page?which=setting',
                        'target' => '_self'
                    ]
                ]
            ], [
                'title' => '插件管理',
                'icon' => 'fa fa-compass',
                'href' => '',
                'target' => '_self',
                'child' => $pluginPages
            ]

        ];

        return json_encode([
            "homeInfo" => [
                'title' => '首页',
                'href' => '/admin/page?which=welcome'
            ],
            "logoInfo" => [
                'title' => 'LyMaster',
                'image' => '/resource/icon/LyAPI.ico',
                'href' => ''
            ],
            "menuInfo" => $menuInfo
        ]);
    }

    // 安全防护系统程序
    public function security()
    {
        $program = Request::Get("program");

        if ($program == "retrieve") {
            $cache = DI::FileCache("security");

            if (Request::Get("clean") != "true") {
                if ($cache->has("pwd-backup")) {
                    $pwd = $cache->get("pwd-backup");

                    if (Request::Get("only") == "true") {
                        return $pwd;
                    } else {
                        return "<h3>初始密码备份系统:</h3>" .
                            "<p>Admin 默认初始密码为 <strong>" . $pwd . "</strong> " .
                            "[两小时内销毁备份]</p>" .
                            "<a href='?program=retrieve&clean=true'>立刻销毁备份</a>";
                    }
                } else {
                    return "备份密码已销毁，查询失败...";
                }
            } else {
                $cache->delete("pwd-backup");
                return "备份密码已删除，后续将无法通过本页面查询密码...";
            }
        }

        return Error::runtimeError([
            'title' => '未知的操作程序',
            'info' => '操作异常: 未知的操作程序库',
            'tail' => '系统安全保护程序'
        ]);
    }

    // 代码生成器渲染程序
    public function coder()
    {

        $open_overview = Config::getConfig('summit', 'admin', 'json')['coder']['open_overview'];

        // 处理子页面请求
        if (Request::Get('child') != '') {
            $child_page = Request::Get('child');
            if ($child_page == 'overview') {
                if ($open_overview) {
                    // 验证用户身份
                    if (Verify::isLogin()) {
                        if (Verify::authCheck('docoder')) {
                            return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/coder/overview.html'), []);
                        }
                    }
                    return '您没有权限进入本页面';
                } else {
                    return 'OverView系统未开启...';
                }
            } else if ($child_page == 'sysinfo') {
                // 系统信息页面
                if (Verify::isLogin()) {
                    $LyMaster = new LyMaster();
                    return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/coder/sysinfo.html'), [
                        'server_type' => php_uname('s') . php_uname('r'),
                        'php_ver' => PHP_VERSION,
                        'LyMaster_ver' => $LyMaster->GetPluginVersion()
                    ]);
                }
            } else if ($child_page == 'cmder') {
                if (Verify::isLogin()) {
                    $LyMaster = new LyMaster();
                    return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/coder/cmder.html'), [
                        'server_type' => php_uname('s') . php_uname('r'),
                        'php_ver' => PHP_VERSION,
                        'LyMaster_ver' => $LyMaster->GetPluginVersion()
                    ]);
                }
            }
        }

        // coder 配置读取
        $config = Config::getConfig('coder', 'admin', 'json');

        $theme = $config['default-theme'];

        $nowfile = '';
        $nowtype = '';

        if (Request::Get('from') != '') {

            $from = str_replace('\\', '/', Request::Get('from'));
            $from = str_replace('..', '', $from);


            $fpath = LyApi . '/app/api/' . $from . '.php';
            if (file_exists($fpath)) {
                $context = file_get_contents($fpath);
                $language = $config['default-language'];
                $nowfile = Request::Get('from') . '.php';
                $nowtype = 'api';
            }
        } else {
            $context = file_get_contents(LyApi . '/admin/coder/welcome.md');
            $language = 'markdown';
        }

        $readonly = false;
        $islogin = true;

        if (Request::Get('language') != '') {
            $language = Request::Get('language');
        }

        if (!Verify::isLogin()) {
            if ($config['public-view'] != 'open' && $config['public-view'] != 'readonly') {
                $language = 'text';
                $context = '您还未登陆账号，将无法正常访问 Coder 代码编辑器。';

                $readonly = true;
                $islogin = false;
            } elseif ($config['public-view'] == 'readonly') {
                $readonly = true;
            }
            $open_overview = false;
        }

        if (!Verify::authCheck('docoder')) {
            $open_overview = false;
        }

        $overview_often = [];
        if ($open_overview) {
            $overview_often = Config::getConfig('coder', 'admin', 'json')['overview_often'];
            if ($overview_often != []) {
                // 验证是否符合规则
                foreach ($overview_often as $key => $value) {
                    if (gettype($value) == 'array') {
                        if (!(array_key_exists('title', $value) && array_key_exists('file', $value) && array_key_exists('path', $value))) {
                            $overview_often = [];
                            break;
                        }
                    } else {
                        $overview_often = [];
                        break;
                    }
                }
            }
        }

        return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/coder/coder.html'), [
            'domain' => $this->resources->Domain(),
            'token' => Request::Get('token'),

            'fontsize' => $config['font-size'],
            'language' => $language,
            'theme' => $theme,

            'code' => $context,
            'readonly' => $readonly,
            'islogin' => $islogin,

            'nowfile' => $nowfile,
            'nowtype' => $nowtype,

            'overview' => $open_overview,
            'use_ovoften' => count($overview_often) > 0,
            'overview_often' => $overview_often,

            'apis' => Launch::LaunchApi('APP\\api\\admin\\api\\apis', 'trees')['data'],
            'makers' => Launch::LaunchApi('APP\\api\\admin\\api\\maker', 'comps')['data']
        ]);
    }

    // 接口创造者页面
    public function maker()
    {

        if (!Verify::isLogin()) {
            return "账号未登录";
        }

        return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/maker/maker.html'), [
            "comps" => Launch::LaunchApi("APP\api\admin\api\maker", "component", ["do" => "list"])['data']
        ]);
    }

    // 接口创造者页面
    public function cmder()
    {

        if (!Verify::isLogin()) {
            return "账号未登录";
        }

        return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/coder/cmder.html'), [
            'domain' => $this->resources->Domain()
        ]);
    }

    // 信息中心渲染
    public function message()
    {
        if (!Verify::isLogin()) {
            return "账号未登录";
        }

        $do = Request::Get('do');
        if ($do == "kan") {
            $id = Request::Get('id');
            $msg = Notification::getMesssage($id);
            return Template::RenderTemplate($msg['context'], [
                'layid' => $id
            ]);
        }

        $msgs = Notification::messageList();

        if (gettype($msgs) == 'array') {
            foreach ($msgs as $key => $value) {
                if ($value['type'] == 'info') {
                    $msgs[$key]['type'] = '系统提示';
                } else if ($value['type'] == 'error') {
                    $msgs[$key]['type'] = '系统异常';
                } else if ($value['type'] == 'warning') {
                    $msgs[$key]['type'] = '系统警告';
                } else if ($value['type'] == 'success') {
                    $msgs[$key]['type'] = '成功信息';
                } else {
                    $msgs[$key]['type'] = '未知类型';
                }
            }
        }

        return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/user/message.html'), [
            'domain' => $this->resources->Domain(),
            'messages' => $msgs
        ]);
    }

    // 管理系统子页面渲染
    public function page()
    {

        if (!Verify::isLogin()) {
            return '当前状况：未登录';
        }

        $type = Request::Get('type');
        $which = Request::Get('which');

        // 过滤无参数访问
        if ($which == '') {
            return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/page/404.html'), [
                'domain' => $this->resources->Domain()
            ]);
        }

        // 数据库取得连接
        $db_connect = Setting::dbConnect();

        $LyMaster = new LyMaster();

        $path = LyApi . '/app/view/html/admin/page/';
        $vars = [
            'domain' => $this->resources->Domain(),
            'resource' => $this->resources->Domain() . '/resource/admin/'
        ];

        // 判断渲染目标
        if ($type == '' && $which == 'welcome') {
            $path .= 'welcome.html';

            // 页面渲染数据
            $vars['adVersion'] = $this->admin_plugin->GetPluginVersion();
            $vars['apisNum'] = $db_connect->count('apis');
            $vars['allVis'] = $LyMaster->visitState('all');


            $updinfo = file_get_contents(LyApi . '/update.json');
            $updinfo = json_decode($updinfo, true);

            $master = DI::LyMaster();
            $version = $master->GetPluginVersion();

            foreach ($updinfo as $key => $value) {
                if($version == $value["title"]){
                    $updinfo[$key]['title'] .= " [当前]";
                }
            }

            $vars["updInfo"] = $updinfo;

            if (!function_exists("imagefttext")) {
                $vars['perilNum'] = 1;
            } else {
                $vars['perilNum'] = 0;
            }
        } else {
            if ($type == '') {
                if ($which == 'self-setting') {
                    $path .= 'self-setting.html';
                    $vars['username'] = $_SESSION['username'];
                    $vars['nickname'] = $_SESSION['nickname'];
                    $vars['email'] = $db_connect->get('users', 'email', ['username' => $_SESSION['username']]);
                } elseif ($which == 'setting') {

                    if (!Verify::authCheck("dosetting")) {
                        return Error::runtimeError([
                            'title' => '无访问权限',
                            'info' => '权限异常: 当前账号无操作权限',
                            'tail' => '后台权限保护程序'
                        ]);
                    }

                    $path .= 'setting.html';
                    // 加载系统数据
                    $vars['settings'] = [];

                    $setting_list = $db_connect->select('setting', '*');
                    foreach ($setting_list as $key => $value) {
                        $vars['settings'][$setting_list[$key]['comment']] = $setting_list[$key]['context'];
                    }
                } elseif ($which == 'develop-setting') {
                    // 开发设置程序

                    if (Verify::authCheck("dosetting")) {
                        $path .= 'develop/setting.html';
                        $vars['context'] = file_get_contents(LyApi . '/config/admin/develop.json');
                    } else {
                        return Error::runtimeError([
                            'title' => '无访问权限',
                            'info' => '权限异常: 当前账号无操作权限',
                            'tail' => '后台权限保护程序'
                        ]);
                    }
                }
            } elseif ($type == 'apis') {
                $path .= 'apis/';

                // 接口列表页面数据
                if ($which == 'list') {
                    $path .= 'list.html';
                    $vars['count'] = Launch::LaunchApi('APP\api\admin\api\apis', 'count')['data'];
                } else if ($which == 'list.add') {
                    // 接口创建程序
                    if (Request::Get('maker') == 't') {
                        $vars['maker'] = true;
                    }
                    $path .= 'add.html';
                }
            } else if ($type == 'template') {
                // 模板页面渲染
                $path .= 'templates/';
                if ($which == 'list') {
                    $path .= 'list.html';
                }
            } else if ($type == 'users') {
                // 用户信息渲染区

                $path .= 'users/';

                if ($which == 'list') {
                    $path .= 'list.html';
                } else if ($which == 'user.add') {

                    if (!Verify::isLogin()) {
                        return Error::_404Error();
                    } else if (!Verify::authCheck("douser")) {
                        return Error::runtimeError([
                            'title' => '无访问权限',
                            'info' => '权限异常: 当前账号无操作权限',
                            'tail' => '后台权限保护程序'
                        ]);
                    }

                    $path .= 'add.html';
                    $vars['acfrom'] = 'ureg:' . $_SERVER['REMOTE_ADDR'];
                    $vars['cverify'] = function_exists("imagefttext");
                } else if ($which == 'user.edit') {

                    if (!Verify::isLogin()) {
                        return Error::_404Error();
                    } else if (!Verify::authCheck("douser")) {
                        return Error::runtimeError([
                            'title' => '无访问权限',
                            'info' => '权限异常: 当前账号无操作权限',
                            'tail' => '后台权限保护程序'
                        ]);
                    }

                    if (Request::Get('user') != '') {
                        if ($db_connect->has('users', ['id' => Request::Get('user')])) {
                            $path .= 'edit.html';
                            $vars['acfrom'] = 'uupd:' . $_SERVER['REMOTE_ADDR'];
                            $vars['udata'] = $db_connect->get('users', ['username', 'nickname', 'usable', 'email'], [
                                'id' => Request::Get('user')
                            ]);
                            $vars['isok'] = $vars['udata']['usable'] == '1';
                            $vars['userid'] = Request::Get('user');
                            $vars['cverify'] = function_exists("imagefttext");
                        } else {
                            return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/page/404.html'), [
                                'domain' => $this->resources->Domain()
                            ]);
                        }
                    } else {
                        return '非法的页面请求...';
                    }
                } else if ($which  == 'level.list') {
                    $path .= 'level/list.html';
                }
            } else if ($type == 'dbs') {
                $path .= 'dbs/';

                if ($which == 'list') {
                    $path .= 'list.html';
                    $vars['count'] = Launch::LaunchApi('APP\api\admin\api\dbs', 'count')['data'];
                } else if ($which == 'dbs.add') {
                    $path .= 'add.html';
                } else if ($which == 'sql') {
                    $path .= 'sql.html';
                    $vars['dblist'] = $db_connect->select("database", ["id", "name"]);
                }
            }
        }

        // 查找文件并进行渲染
        if (file_exists($path) && is_file($path)) {
            return Template::RenderTemplate(file_get_contents($path), $vars);
        } else {
            return Template::RenderTemplate(file_get_contents(LyApi . '/app/view/html/admin/page/404.html'), [
                'domain' => $this->resources->Domain()
            ]);
        }
    }

    // 插件操作根程序
    public function plugin($type, $args)
    {
        // 在本处写代码太麻烦，转发到Plugin对象下
        $obj = new plugin();
        return $obj->__page('TRANS', $args);
    }

    // 展示一些未运行的代码程序
    public function show()
    {
        $type = Request::Get('type');
        if ($type == 'template') {
            $id = Request::Get('id');
            if ($id != '') {
                $db_connect = Setting::dbConnect();
                if ($db_connect->has('api_templates', ['id' => $id])) {

                    $this->SetHeader('Content-type: application/json');
                    $this->SetHeader('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');

                    $path = $db_connect->get('api_templates', 'path', ['id' => $id]);
                    return file_get_contents(LyApi . '/admin/template/' . $path);
                }
            }
        } else if ($type == 'makerc') {
        }

        return Error::runtimeError([
            'title' => '未知的目标内容',
            'info' => '渲染异常: 无法找到目标内容',
            'tail' => '无法找到目标内容'
        ]);
    }

    // 框架调试页面
    public function debug()
    {

        if (LyMaster::isDebug()) {
            $type = Request::Get('type');
            if ($type == 'tree') {
                if (Request::Get("detail") != '') {
                    return json_encode(Register::Get(Request::Get("detail")));
                }
                return "测试环境树获取：" . json_encode(Register::Lists());
            }
            return '<h2>LyApi Admin Debug 程序</h2>';
        }

        Error::_404Error();
    }
}
